const { validationResult } = require('express-validator');
const { AppError } = require('./errorHandler');

// 验证请求数据
const validate = (req, res, next) => {
  const errors = validationResult(req);
  
  if (!errors.isEmpty()) {
    const errorMessages = errors.array().map(error => ({
      field: error.path,
      message: error.msg,
      value: error.value
    }));

    return next(new AppError('Validation failed', 400, errorMessages));
  }
  
  next();
};

// 通用验证规则
const commonValidations = {
  // 用户相关验证
  user: {
    email: {
      in: ['body'],
      isEmail: {
        errorMessage: 'Please provide a valid email address'
      },
      normalizeEmail: true
    },
    password: {
      in: ['body'],
      isLength: {
        options: { min: 6, max: 128 },
        errorMessage: 'Password must be between 6 and 128 characters'
      }
    },
    name: {
      in: ['body'],
      isLength: {
        options: { min: 2, max: 50 },
        errorMessage: 'Name must be between 2 and 50 characters'
      },
      trim: true
    }
  },

  // ID验证
  id: {
    in: ['params'],
    isMongoId: {
      errorMessage: 'Invalid ID format'
    }
  },

  // 分页验证
  pagination: {
    page: {
      in: ['query'],
      optional: true,
      isInt: {
        options: { min: 1 },
        errorMessage: 'Page must be a positive integer'
      },
      toInt: true
    },
    limit: {
      in: ['query'],
      optional: true,
      isInt: {
        options: { min: 1, max: 100 },
        errorMessage: 'Limit must be between 1 and 100'
      },
      toInt: true
    }
  }
};

module.exports = {
  validate,
  commonValidations
};
